#include "adalog/appender/BackupAppender.h"
#include "adalog/Logger.h"
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

namespace adalog 
{
    BackupAppender::BackupAppender(const std::string& address, int port)
    {
        conn_fd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (conn_fd_ < 0)
            ADALOG_DEFAULT_ERROR(std::string("socket error : ") + strerror(errno));
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(static_cast<uint16_t>(port));
        inet_aton(address.c_str(), &(server.sin_addr));
        int cnt = 5;
        while (-1 == connect(conn_fd_, (struct sockaddr*)&server, sizeof(server)))
        {
            ADALOG_DEFAULT_INFO(std::string("正在尝试重连日志备份服务器，重连次数剩余: ") + std::to_string(cnt--));
            if (cnt <= 0)
            {
                ADALOG_DEFAULT_ERROR("日志备份服务器连接失败");
                close(conn_fd_);
                conn_fd_ = -1;
                return;
            }
        }
    }

    BackupAppender::~BackupAppender()
    {
        if (conn_fd_ > 0)
        {
            close(conn_fd_);
            conn_fd_ = -1;
        }
    }

    void BackupAppender::Append(const char* data, size_t len)
    {
        if (-1 == write(conn_fd_, data, len))
            ADALOG_DEFAULT_ERROR(std::string("write error : ") + strerror(errno));
    }


} // namespace adalog